import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import * as accountApi from '@/api/account'
import type { Account, AccountStats, AccountQueryParams } from '@/api/account'
import { createCrypto, EncryptMethod } from '@/utils/crypto'
import { accountStorage } from '@/utils/storage'

export const useAccountStore = defineStore('account', () => {
  // 状态
  const accounts = ref<Account[]>([])
  const favoriteAccounts = ref<Account[]>([])
  const accountStats = ref<AccountStats | null>(null)
  const currentAccount = ref<Account | null>(null)
  const isLoading = ref(false)
  const searchKeyword = ref('')

  // 加密配置
  const encryptConfig = ref({
    method: EncryptMethod.AES_256_GCM,
    masterPassword: ''
  })

  // 计算属性
  const filteredAccounts = computed(() => {
    if (!searchKeyword.value) {
      return accounts.value
    }

    const keyword = searchKeyword.value.toLowerCase()
    return accounts.value.filter(account =>
      account.title.toLowerCase().includes(keyword) ||
      account.website?.toLowerCase().includes(keyword) ||
      account.username?.toLowerCase().includes(keyword)
    )
  })

  const accountsByCategory = computed(() => {
    const groups: Record<string, Account[]> = {}

    filteredAccounts.value.forEach(account => {
      const categoryName = account.category?.name || '未分类'
      if (!groups[categoryName]) {
        groups[categoryName] = []
      }
      groups[categoryName].push(account)
    })

    return groups
  })

  const recentAccounts = computed(() => {
    return accounts.value
      .filter(account => account.last_used_at)
      .sort((a, b) => {
        const timeA = new Date(a.last_used_at!).getTime()
        const timeB = new Date(b.last_used_at!).getTime()
        return timeB - timeA
      })
      .slice(0, 10)
  })

  const expiringAccounts = computed(() => {
    const now = new Date()
    const sevenDaysLater = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000)

    return accounts.value.filter(account => {
      if (!account.expires_at) return false
      const expiresAt = new Date(account.expires_at)
      return expiresAt <= sevenDaysLater && expiresAt > now
    })
  })

  /**
   * 设置加密配置
   */
  const setEncryptConfig = (config: Partial<typeof encryptConfig.value>) => {
    encryptConfig.value = { ...encryptConfig.value, ...config }
  }

  /**
   * 获取加密工具
   */
  const getCrypto = () => {
    if (!encryptConfig.value.masterPassword) {
      throw new Error('主密码未设置')
    }
    return createCrypto(encryptConfig.value)
  }

  /**
   * 加载账号列表
   */
  const loadAccounts = async (params?: AccountQueryParams) => {
    try {
      isLoading.value = true

      const accountList = await accountApi.getAccounts(params)

      // 如果有主密码，解密账号数据
      if (encryptConfig.value.masterPassword) {
        const crypto = getCrypto()
        accounts.value = accountList.map(account =>
          accountStorage.loadAccount(account, crypto)
        )
      } else {
        accounts.value = accountList
      }

      return accounts.value

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 加载收藏账号
   */
  const loadFavoriteAccounts = async () => {
    try {
      const favoriteList = await accountApi.getFavoriteAccounts()

      if (encryptConfig.value.masterPassword) {
        const crypto = getCrypto()
        favoriteAccounts.value = favoriteList.map(account =>
          accountStorage.loadAccount(account, crypto)
        )
      } else {
        favoriteAccounts.value = favoriteList
      }

      return favoriteAccounts.value

    } catch (error) {
      throw error
    }
  }

  /**
   * 加载账号统计
   */
  const loadAccountStats = async () => {
    try {
      accountStats.value = await accountApi.getAccountStats()
      return accountStats.value
    } catch (error) {
      throw error
    }
  }

  /**
   * 获取账号详情
   */
  const getAccountDetail = async (id: number) => {
    try {
      isLoading.value = true

      const account = await accountApi.getAccountDetail(id)

      // 解密账号数据
      if (encryptConfig.value.masterPassword) {
        const crypto = getCrypto()
        currentAccount.value = accountStorage.loadAccount(account, crypto)
      } else {
        currentAccount.value = account
      }

      return currentAccount.value

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 创建账号
   */
  const createAccount = async (accountData: Omit<Account, 'id' | 'user_id' | 'created_at' | 'updated_at'>) => {
    try {
      isLoading.value = true

      // 加密账号数据
      const crypto = getCrypto()
      const encryptedAccount = accountStorage.saveAccount(accountData, crypto)

      const newAccount = await accountApi.createAccount(encryptedAccount)

      // 解密并添加到列表
      const decryptedAccount = accountStorage.loadAccount(newAccount, crypto)
      accounts.value.unshift(decryptedAccount)

      return decryptedAccount

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 更新账号
   */
  const updateAccount = async (id: number, accountData: Partial<Account>) => {
    try {
      isLoading.value = true

      // 加密账号数据
      const crypto = getCrypto()
      const encryptedAccount = accountStorage.saveAccount(accountData, crypto)

      const updatedAccount = await accountApi.updateAccount(id, encryptedAccount)

      // 解密并更新列表
      const decryptedAccount = accountStorage.loadAccount(updatedAccount, crypto)

      const index = accounts.value.findIndex(account => account.id === id)
      if (index !== -1) {
        accounts.value[index] = decryptedAccount
      }

      if (currentAccount.value?.id === id) {
        currentAccount.value = decryptedAccount
      }

      return decryptedAccount

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 删除账号
   */
  const deleteAccount = async (id: number) => {
    try {
      isLoading.value = true

      await accountApi.deleteAccount(id)

      // 从列表中移除
      accounts.value = accounts.value.filter(account => account.id !== id)
      favoriteAccounts.value = favoriteAccounts.value.filter(account => account.id !== id)

      if (currentAccount.value?.id === id) {
        currentAccount.value = null
      }

      // 更新统计
      if (accountStats.value) {
        accountStats.value.total -= 1
      }

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 切换收藏状态
   */
  const toggleFavorite = async (id: number) => {
    try {
      const updatedAccount = await accountApi.toggleAccountFavorite(id)

      // 解密账号数据
      const crypto = getCrypto()
      const decryptedAccount = accountStorage.loadAccount(updatedAccount, crypto)

      // 更新列表
      const index = accounts.value.findIndex(account => account.id === id)
      if (index !== -1) {
        accounts.value[index] = decryptedAccount
      }

      // 更新收藏列表
      if (decryptedAccount.is_favorite) {
        favoriteAccounts.value.push(decryptedAccount)
      } else {
        favoriteAccounts.value = favoriteAccounts.value.filter(account => account.id !== id)
      }

      if (currentAccount.value?.id === id) {
        currentAccount.value = decryptedAccount
      }

      return decryptedAccount

    } catch (error) {
      throw error
    }
  }

  /**
   * 复制密码
   */
  const copyPassword = async (id: number) => {
    try {
      const account = accounts.value.find(a => a.id === id)
      if (!account || !account.password) {
        throw new Error('密码不存在')
      }

      // 复制到剪贴板
      await uni.setClipboardData({
        data: account.password
      })

      // 记录复制操作
      await accountApi.copyAccountPassword(id)

      // 更新最后使用时间
      account.last_used_at = new Date().toISOString()

      uni.showToast({
        title: '密码已复制',
        icon: 'success'
      })

    } catch (error) {
      throw error
    }
  }

  /**
   * 搜索账号
   */
  const searchAccounts = async (keyword: string) => {
    try {
      if (!keyword.trim()) {
        searchKeyword.value = ''
        return accounts.value
      }

      searchKeyword.value = keyword

      // 如果本地搜索结果足够，使用本地搜索
      if (accounts.value.length > 0) {
        return filteredAccounts.value
      }

      // 否则调用API搜索
      const searchResults = await accountApi.searchAccounts(keyword)

      if (encryptConfig.value.masterPassword) {
        const crypto = getCrypto()
        return searchResults.map(account =>
          accountStorage.loadAccount(account, crypto)
        )
      }

      return searchResults

    } catch (error) {
      throw error
    }
  }

  /**
   * 批量删除账号
   */
  const batchDeleteAccounts = async (accountIds: number[]) => {
    try {
      isLoading.value = true

      const result = await accountApi.batchDeleteAccounts(accountIds)

      // 从列表中移除
      accounts.value = accounts.value.filter(account => !accountIds.includes(account.id))
      favoriteAccounts.value = favoriteAccounts.value.filter(account => !accountIds.includes(account.id))

      return result

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 导出账号数据
   */
  const exportAccounts = async (categoryId?: number) => {
    try {
      isLoading.value = true

      const exportData = await accountApi.exportAccounts(categoryId)

      // 解密数据
      if (encryptConfig.value.masterPassword) {
        const crypto = getCrypto()
        return exportData.map(account =>
          accountStorage.loadAccount(account, crypto)
        )
      }

      return exportData

    } catch (error) {
      throw error
    } finally {
      isLoading.value = false
    }
  }

  /**
   * 清空搜索
   */
  const clearSearch = () => {
    searchKeyword.value = ''
  }

  /**
   * 重置状态
   */
  const resetState = () => {
    accounts.value = []
    favoriteAccounts.value = []
    accountStats.value = null
    currentAccount.value = null
    searchKeyword.value = ''
    encryptConfig.value = {
      method: EncryptMethod.AES_256_GCM,
      masterPassword: ''
    }
  }

  return {
    // 状态
    accounts,
    favoriteAccounts,
    accountStats,
    currentAccount,
    isLoading,
    searchKeyword,
    encryptConfig,

    // 计算属性
    filteredAccounts,
    accountsByCategory,
    recentAccounts,
    expiringAccounts,

    // 方法
    setEncryptConfig,
    getCrypto,
    loadAccounts,
    loadFavoriteAccounts,
    loadAccountStats,
    getAccountDetail,
    createAccount,
    updateAccount,
    deleteAccount,
    toggleFavorite,
    copyPassword,
    searchAccounts,
    batchDeleteAccounts,
    exportAccounts,
    clearSearch,
    resetState
  }
})